#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_freertos_hooks.h"
#include "freertos/semphr.h"
#include "esp_system.h"
#include "esp_log.h"
#include "clock.h"
#include "http_client.h"
#include "sntp.h"
#include "screen.h"



static const char* TAG = "clock";

extern xQueueHandle screen_event_queue;


void clock_task(void *pParam)
{
    vTaskDelay(5000 / portTICK_RATE_MS);
    initialize_time();
    screen_event_t screent_event;
    int every_n = 60;
    int count = 0;
    while(1) {
        print_time();
        screent_event.type = S_EVENT_UPDATE_CLOCK;
        xQueueSend(screen_event_queue, &screent_event, portMAX_DELAY);
        count++;
        if(count % every_n == 0) {
            initialize_time();
        }
        vTaskDelay(1000*60 / portTICK_RATE_MS);
    }
    vTaskDelete(NULL);
}

void initialize_time()
{
    time_t now;
    struct tm timeinfo;
    time(&now);
    localtime_r(&now, &timeinfo);
    // Is time set? If not, tm_year will be (1970 - 1900).
    if (timeinfo.tm_year < (2016 - 1900)) {
        ESP_LOGI(TAG, "Time is not set yet. Connecting to WiFi and getting time over NTP.");
        obtain_time();
        // update 'now' variable with current time
        time(&now);
    }

}

void print_time()
{
    time_t now;
    struct tm timeinfo;
    time(&now);
    localtime_r(&now, &timeinfo);
    
    char strftime_buf[64];

    // Set timezone to China Standard Time
    setenv("TZ", "CST-8", 1);
    tzset();
    localtime_r(&now, &timeinfo);
    strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo);
    ESP_LOGI(TAG, "The current date/time in Shanghai is: %s", strftime_buf);    
}